import axios from 'axios'
import qs from 'qs'
import { ElLoading, ElMessage } from 'element-plus'
// import store from '@/store'
import {useLocaleStore} from '../store/locales.js'
import { getQueryVariable } from '@/utils/index.js'

// axios实例
const service = axios.create({
	baseURL: '/api/swBackApi',
	timeout: 60000
})

// 请求拦截器
service.interceptors.request.use(
	(config) => {

    const useLocale = useLocaleStore()
    let curLocale = 1
		let queryParams = getQueryVariable()

		if (queryParams?.language == 1 || queryParams?.language == 2) {
      curLocale = queryParams?.language
		} else {
      curLocale = useLocale.locale === 'en' ? 2 : 1
		}

		// 追加时间戳，防止GET请求缓存
		if (config.method?.toUpperCase() === 'GET') {
			config.params = { ...config.params, t: new Date().getTime(), 'language': curLocale }
		}

		if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
			config.data = qs.stringify(config.data)
		}
    if (config.method?.toUpperCase() === 'POST') {
      config.data.language = curLocale
    }
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use(response => {
  if (response.status !== 200) {
    return Promise.reject(new Error(response.statusText || 'Error'))
  }

  const res = response.data
  // 响应成功
  // if (res.code == 0) {
	return res
  // }

  // 没有权限，如：未登录、登录过期等，需要跳转到登录页
  // if (res.code === '402') {
  // 	localStorage.clear() // 清楚token
  //   location.href = '/#/login'
  // } else {
  //   // 错误提示
  // 	ElMessage.error(res.msg)
	// }
  // return Promise.reject(new Error(res.msg || 'Error'))
}, error => {
  return Promise.reject(error)
})

/*
 * 有全局loading的请求方法
 * 使用示例：
 * import {request} from '@/utils/request'
 * return request({
 *    url: '/sys/auth/login',
 *    method: 'post',
 *	   data: data
 * })
 * */
export const request = (options, { loading = true, message = '加载中...' } = {}) => {
	let loadingInstance = ''
	if (loading) {
		loadingInstance = ElLoading.service({
			lock: true,
			text: message,
			background: 'rgba(0, 0, 0, 0.7)'
		})
	}
	return new Promise((resolve, reject) => {
		service(options)
			.then(resolve)
			.catch(reject)
			.finally(() => {
				if (loading) {
					loadingInstance.close()
				}
			})
	})
}
